<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!--
      Tips: 在van-search 外层添加form标签, 且action不为空. 即可在ios 输入法中显示搜索按钮
     -->
    <van-form>
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search = 'onSearch'
        @cancel = '$router.back()'
        @focus = "isResultShow = false"
      ></van-search>
    </van-form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-text='searchText'/>
    <!-- 联想建议 -->
    <search-suggestion v-else-if="searchText" :search-text='searchText' @search='onSearch'/>
    <!-- 历史记录 -->
    <search-history v-else :search-histories='searchHistories' @search='onSearch' @unpdate-histories='searchHistories = $event'/>
  </div>
</template>

<script>
import SearchSuggestion from './components/search-suggestion'
import SearchHistory from './components/search-history'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
// import { getSearchHistories } from '@/api/search'
import { mapState } from 'vuex'
export default {
  name: 'SearchIndex',
  components: {
    SearchSuggestion,
    SearchHistory,
    SearchResult
  },
  props: {},
  data () {
    return {
      searchText: '', // 搜索关键词
      isResultShow: false, // 控制搜素结果的显示状态
      searchHistories: getItem('search-histories') || [] // 搜索历史及记录
    }
  },
  computed: {
    ...mapState(['user'])
  },
  watch: {
    searchHistories () {
      setItem('search-histories', this.searchHistories)
    }
  },
  async mounted () {
    this.loadSearchHistories()
  },
  methods: {
    onSearch (searchText) {
      this.searchText = searchText

      const index = this.searchHistories.indexOf(searchText)
      if (index !== -1) {
        // 把重复项移除
        this.searchHistories.splice(index, 1)
      }
      // 记录历史记录(把搜索项放到第一)
      this.searchHistories.unshift(searchText)
      // 如果用户已经登录, 则把搜索历史记录存到线上( 后端自己记录 )
      // 如果没有登录, 则把搜索的历史记录存到本地即可
      // setItem('search-histories', this.searchHistories) // 在全局watch监视发生变化就更新缓存
      this.isResultShow = true
    },
    // 获取历史及记录
    async loadSearchHistories () {
      // 因为后端只给我们返回了四条历史搜索记录(缺点)
      // 所以我们这里让后端返回的历史记录和本地的历史记录合并在一起
      // 会有重复项, 使用lodash.uniq()函数去重, 或者自己写 new Set()
      const searchHistories = getItem('search-histories') || []

      // if (this.user) {
      // const { data } = await getSearchHistories()
      // console.log(data.data.kwywords)
      //   searchHistories = Array.from(new Set([
      //     ...searchHistories,
      //     ...data.data.keywords
      //   ]))
      // }
      this.searchHistories = searchHistories
    }
  }
}

</script>
<style lang='less' scoped>
</style>
